<template>
  <view class="container">
    <!-- 顶部 Logo -->
    <view class="logo-container">
      <!-- 添加返回按钮 -->
      <view class="back-button" @click="goBack">
        <u-icon name="arrow-left" size="20"></u-icon>
      </view>
      <image class="logo-bg" src="/static/img/register.png" />
      <text class="title">用户注册</text>
      <view class="tabs-wrapper">
        <up-tabs
          class="up-tabs-content"
          :list="tabsData"
          @click="onTabClick"
          :current="activeTab"
          :lineWidth="lineWidth"
          lineColor="#2877FF"
          :activeStyle="{
            color: '#2877FF',
            fontWeight: '500',
            fontSize: '16px',
          }"
          :inactiveStyle="{
            color: '#0D1444',
            fontWeight: '500',
            fontSize: '16px',
          }"
          itemStyle="padding-left: 15px; padding-right: 15px; height: 50px;"
        />
      </view>
    </view>
    <!-- 表单内容 -->
    <view class="register-form-wrapper">
      <u-form
        class="register-form"
        :model="registerData"
        ref="registerForm"
        :rules="rules"
      >
        <!-- 统一社会信用代码 / 身份证号码 -->
        <u-form-item
          :label="userType === 'business' ? '统一社会信用代码' : '身份证号'"
          prop="idOrCode"
          :label-width="80"
        >
          <u-input
            class="custom-input"
            v-model="registerData.idOrCode"
            :placeholder="
              userType === 'business'
                ? '请输入统一社会信用代码'
                : '请输入身份证号'
            "
          />
        </u-form-item>

        <!-- 用户名 -->
        <u-form-item label="用户名" prop="username" label-width="80">
          <u-input
            class="custom-input"
            v-model="registerData.username"
            placeholder="请输入用户名"
          />
        </u-form-item>

        <!-- 密码 -->
        <u-form-item label="密码" prop="password" label-width="80">
          <u-input
            class="custom-input"
            v-model="registerData.password"
            type="password"
            placeholder="请输入密码"
          />
        </u-form-item>

        <!-- 确认密码 -->
        <u-form-item label="确认密码" prop="confirmPassword" label-width="80">
          <u-input
            class="custom-input"
            v-model="registerData.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
          />
        </u-form-item>

        <!-- 手机号码 -->
        <u-form-item label="手机号码" prop="phoneNumber" label-width="80">
          <view class="sms-code-container">
            <u-input
              class="custom-input"
              v-model="registerData.phoneNumber"
              placeholder="请输入手机号"
            />
            <view class="divider"></view>
            <u-button
              class="send-code-btn"
              type="text"
              :disabled="isSending || countdown > 0"
              @click="sendSmsCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : "获取验证码" }}
            </u-button>
          </view>
        </u-form-item>

        <!-- 验证码 -->
        <u-form-item label="验证码" prop="smsCode" label-width="80">
          <u-input
            class="custom-input"
            v-model="registerData.smsCode"
            placeholder="请输入验证码"
          />
        </u-form-item>

        <!-- 注册按钮 -->
        <view class="register-button-wrapper">
          <u-button type="primary" @click="signForm" class="register-button"
            >立即注册</u-button
          >
        </view>
      </u-form>
    </view>
  </view>
</template>

<script>
import {
  registerEnt,
  registerPerson,
  sendPhoneCode,
} from "@/common/api/req.js";

export default {
  data() {
    return {
      // 用户类型切换 Tabs 数据
      tabsData: [
        {
          name: "企业用户",
          id: "business",
        },
        {
          name: "个人用户",
          id: "personal",
        },
      ],
      // 当前选中的用户类型
      userType: "personal",
      // 下划线宽度
      lineWidth: 60,
      userType: "business", // 默认选中企业用户
      registerData: {
        idOrCode: "", // 统一社会信用代码或身份证号码
        username: "",
        password: "",
        confirmPassword: "",
        phoneNumber: "",
        smsCode: "",
      },
      isSending: false, // 是否正在获取验证码
      countdown: 0, // 倒计时
      activeTab: 0, // 新增：当前激活的tab索引
      rules: {
        idOrCode: [
          {
            required: true,
            message: () =>
              this.userType === "business"
                ? "请输入统一社会信用代码"
                : "请输入身份证号码",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              if (this.userType === "business") {
                // 统一社会信用代码验证逻辑
                if (
                  !/^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/.test(
                    value
                  )
                ) {
                  callback(new Error("请输入正确的统一社会信用代码"));
                } else {
                  callback();
                }
              } else {
                // 身份证号码验证逻辑
                if (!/^(\d{18}|\d{17}X)$/i.test(value)) {
                  callback(new Error("请输入正确的身份证号码"));
                } else {
                  callback();
                }
              }
            },
            trigger: "blur",
          },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value !== this.registerData.password) {
                callback(new Error("两次输入的密码不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
        smsCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
    };
  },
  onLoad(options) {
    if (options.userType) {
      this.userType = options.userType;
      // 根据userType设置activeTab
      this.activeTab = this.userType === "business" ? 0 : 1;
    }
  },
  methods: {
    // Tab 切换处理函数
    onTabClick(event, index) {
      this.userType = event.id;
      this.activeTab = index;
      this.updateLineWidth(index);

      this.resetForm();
    },

    resetForm() {
      // 清空表单数据
      this.clearFormData();

      // 重置表单验证状态并清除所有错误提示
      this.$nextTick(() => {
        if (this.$refs.registerForm) {
          this.$refs.registerForm.resetFields();

          // 清除所有字段的错误提示
          Object.keys(this.rules).forEach((field) => {
            this.$refs.registerForm.clearValidate(field);
          });

          // 更新 idOrCode 字段的验证规则
          this.updateIdOrCodeRule();
        }
      });
    },

    clearFormData() {
      this.registerData = {
        idOrCode: "",
        username: "",
        password: "",
        confirmPassword: "",
        phoneNumber: "",
        smsCode: "",
      };
    },

    updateIdOrCodeRule() {
      this.rules.idOrCode = [
        {
          required: true,
          message:
            this.userType === "business"
              ? "请输入统一社会信用代码"
              : "请输入身份证号码",
          trigger: "blur",
        },
        {
          validator: (rule, value, callback) => {
            if (this.userType === "business") {
              // 统一社会信用代码验证逻辑
              if (
                !/^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/.test(
                  value
                )
              ) {
                callback(new Error("请输入正确的统一社会信用代码"));
              } else {
                callback();
              }
            } else {
              // 身份证号码验证逻辑
              if (!/^(\d{18}|\d{17}X)$/i.test(value)) {
                callback(new Error("请输入正确的身份证号码"));
              } else {
                callback();
              }
            }
          },
          trigger: "blur",
        },
      ];
    },

    // 动态更新 lineWidth
    updateLineWidth(index = 0) {
      // 根据点击的 tab 的内容动态调整 lineWidth

      const tabContent = this.tabsData[index].name;
      const computedWidth = this.calculateTextWidth(tabContent);
      this.lineWidth = computedWidth;
    },
    // 计算文本的实际宽度
    calculateTextWidth(text) {
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      context.font = "16px Arial"; // 设置字体样式（根据你的样式调整）
      const width = context.measureText(text).width;
      return width;
    },
    // 发送短信验证码
    async sendSmsCode() {
      if (this.isSending || this.countdown > 0) return;

      try {
        await this.$refs.registerForm.validateField("phoneNumber");

        const response = await sendPhoneCode({
          phone: this.registerData.phoneNumber,
        });
        if (response.data.code === 200) {
          uni.showToast({ title: "验证码发送成功", icon: "success" });
          this.startCountdown();
        } else {
          uni.showToast({
            title: response.data.message || "发送失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("获取验证码失败:", error);
        uni.showToast({ title: "发送失败，请检查机号", icon: "none" });
      } finally {
        this.isSending = false;
      }
    },
    // 开始倒计时
    startCountdown() {
      this.countdown = 60; // 倒计时 60 秒
      const timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(timer);
        }
      }, 1000);
    },

    async signForm() {
      try {
        // 验证表单，但不清除错误提示
        await this.$refs.registerForm.validate();

        let response;
        const commonData = {
          userName: this.registerData.username,
          password: this.registerData.password,
          confirmPassword: this.registerData.confirmPassword,
          phone: this.registerData.phoneNumber,
          smsVerifyCode: this.registerData.smsCode,
        };

        if (this.userType === "business") {
          response = await registerEnt({
            ...commonData,
            creditCode: this.registerData.idOrCode,
          });
        } else {
          response = await registerPerson({
            ...commonData,
            idCard: this.registerData.idOrCode,
          });
        }

        if (response.data.code === 200) {
          uni.showToast({
            title: "注册成功",
            icon: "success",
            duration: 2000,
          });
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/common/login/login?tab=${
                this.userType === "business" ? "business" : "personal"
              }`,
            });
          }, 2000);
        } else {
          uni.showToast({
            title: response.data.message || "注册失败",
            icon: "none",
            duration: 2000,
          });
        }
      } catch (error) {
        console.error("注册失败:", error);
        // 不清除错误提示，只显示一个通用的错误消息
        uni.showToast({
          title: "注册失败，请检查输入信息",
          icon: "none",
          duration: 2000,
        });
      }
    },

    validateForm() {
      // 实现表单验证逻辑
      // 返回 true 如果验证通过，否则返回 false
    },

    // 添加返回方法
    goBack() {
      uni.navigateTo({
        url: `/pages/common/login/login`,
      });
    },
  },
  created() {
    this.updateIdOrCodeRule();
  },
};
</script>

<style scoped lang="scss">
@import "../login/inputStyles.scss";

/* >>>是深度选择器，不加>>>，在elementUI的form里是选不到label的 */
::v-deep uni-view.u-form-item__body__left {
  text-align: justify;
  text-align-last: justify;
}

.container {
  padding: 0;
  background-color: #fff;
  min-height: 100vh;
}

.logo-container {
  position: relative;
  width: 100%;
  height: 260px;
  overflow: hidden;

  .logo-bg {
    width: 100%;
    height: 100%;
    object-fit: cover;
    position: absolute;
    top: 0;
    left: 0;
  }

  .title {
    position: absolute;
    top: 60%;
    left: 40px;
    transform: translateY(-50%);
    font-size: 22px;
    color: #000;
    font-weight: 500;
    z-index: 2;
  }

  .back-button {
    position: absolute;
    top: 20px;
    left: 10px;
    z-index: 10;
    padding: 5px;
  }

  .tabs-wrapper {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 3;
  }

  .up-tabs-content {
    background-color: transparent;
    padding: 0px 20px;
  }
}

.register-form-wrapper {
  padding-top: 30px; /* 添加这行，设置顶部内边距为30px */
  background-color: #fff;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  margin-top: -20px;
}

.register-form {
  padding: 20px;
}

.sms-code-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f6fc;
  border-radius: 5px;

  box-sizing: border-box;
  flex: 1;

  .divider {
    width: 1px;
    height: 20px;
    background-color: #e7ebf5;
    margin: 0 10px;
  }

  .send-code-btn {
    color: #2877ff;
    width: 80px;
  }
}

/* 可以添加一个新的样式来确保文字样式 */
::v-deep .u-tabs__wrapper__nav__item__text {
  font-weight: 500;
  font-size: 16px;
  color: #0d1444;
}

.register-button-wrapper {
  margin-top: 20px;
}

.register-button {
  background-color: #2877ff !important;
  border-color: #2877ff !important;
}
</style>
